<template>
  <div>
    <!-- 头部面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主题卡片区 -->
    <el-card>
      <!-- 搜索区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="getInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表区 -->
      <el-table :data="userLists" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="changeStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- slot-scope="scope" -->
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle @click="editBtn(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" circle @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getInfo.pagenum"
        :page-sizes="[1, 5, 10, 20,50,100]"
        :page-size="getInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeAddForm">
      <!-- 添加用户 -->
      <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 用户密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <!-- 用户邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 用户手机 -->
        <el-form-item label="用户手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog :visible.sync="setDialogVisible">
      <div>
        <p>用户名:{{userInfo.username}}</p>
        <p>用户角色:{{userInfo.role_name}}</p>
        <p>
          请选择角色:
          <el-select v-model="rolesId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSet">取 消</el-button>
        <el-button type="primary" @click="setDete(userInfo.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      getInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userLists: [],
      total: 0,
      dialogVisible: false,
      editDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      rolesList: [],
      rolesId: '',
      userInfo: {},
      setDialogVisible: false
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const userList = await this.$http.get('users', { params: this.getInfo })
      //   console.log(userList)
      this.userLists = userList.data.users
      this.total = userList.data.total
      //   console.log(this.userLists)
      //   console.log(this.total)
    },
    async changeStatus(val) {
      const res = await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    closeAddForm() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async val => {
        // console.log(val)
        if (!val) return
        const res = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 隐藏添加用户的表单框
        this.dialogVisible = false
        // 重新调用，刷新表单
        this.getUserList()
      })
    },
    async editBtn(val) {
      this.editDialogVisible = true
      const res = await this.$http.get(`users/${val}`)
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    async editUser() {
      this.$refs.editFormRef.validate(async val => {
        if (!val) {
          return this.$message.error('验证失败')
        } else {
          const res = await this.$http.put(
            `users/${this.editForm.id}`,
            this.editForm
          )
          // console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.editDialogVisible = false
          this.getUserList()
        }
      })
    },
    editClose() {
      this.$refs.editFormRef.resetFields()
      this.editDialogVisible = false
    },
    async deleteUser(val) {
      const confirmInfo = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirmInfo)
      if (confirmInfo !== 'confirm') return this.$message.info('您已取消删除')
      await this.$http.delete('users/' + val)
      this.getUserList()
      // console.log(res)
    },
    handleSizeChange(val) {
      console.log(val) // 返回的是当前的每页多少条
      this.getInfo.pagesize = val
      this.getUserList() // 重新加载页面
    },
    handleCurrentChange(val) {
      console.log(val) // 返回的是当前在的页数
      this.getInfo.pagenum = val
      this.getUserList() // 重新加载页面
    },
    // 分配角色
    async setRole(userInfo) {
      // 获取用户信息，渲染到页面
      this.userInfo = userInfo
      this.setDialogVisible = true
      // console.log(userInfo)
      // 获取所有角色,渲染角色下拉框
      const res = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    closeSet() {
      // this.rolesList = []
      // this.userInfo = {}
      this.rolesId = ''
      this.setDialogVisible = false
    },
    async setDete(id) {
      // 发送请求，为用户添加角色
      const res = await this.$http.put(`users/${id}/role`, {
        rid: this.rolesId
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.info('取消角色分配')
      this.$message.success(res.meta.msg)
      this.setDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.el-pagination {
  margin-top: 20px;
}
</style>
